<?php
namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use think\helper\Time;

/**
 * 同步微信公众号用户
 * @author King
 *
 */
class CronSyncWechatUser extends Command
{

	protected $logName = 'cronSyncWechatUser';
	protected $isPrint = 1;	// 是否打印信息到终端

	protected function configure()
	{
		$this->setName('cronSyncWechatUser')
		->addOption('print', 'p', Option::VALUE_OPTIONAL, '是否打印信息到终端(1是，0否)', 1)
		->setDescription('同步微信公众号用户');
	}

	protected function execute(Input $input, Output $output)
	{
		$msg = "开始同步微信公众号用户...";
		$this->isPrint = $input->getOption('print');
		$this->_consoleLog($msg, 'start');

		try {
			$whchat = \We::WeChatUser(config('wechat.'));

			// 获取用户列表
			$response = $whchat->getUserList();
			if ($response['count'] > 0) {
				$list = $response['data']['openid'];

				foreach ($list as $k => $v) {
					$upData = [
						'openid' => $v,
						'update_time' => time(),
					];
					$info = db('wechatUser')->where('openid', $v)->field('id')->find();
					if (!$info) {
						$upData['create_time'] = time();
						db('wechatUser')->insertGetId($upData);
					}
				}

				// 获取用户详情
				$batchList = array_chunk($list, 100);
				foreach ($batchList as $items){
					$response = $whchat->getBatchUserInfo($items);
					foreach ($response['user_info_list'] as $v) {
						if ($v['subscribe'] == 1) {
							$upData = [
								 'nickname' => $v['nickname'],
								 'sex' => $v['sex'],
								 'headimgurl' => $v['headimgurl'],
								 'remark' => $v['remark'],
								 'subscribe' => $v['subscribe'],
								 'country' => $v['country'],
								 'province' => $v['province'],
								 'city' => $v['city'],
								 'subscribe_time' => $v['subscribe_time'],
								 'update_time' => time(),
							];

							// 检测头像是否有更新
							$headimgurl = db('wechatUser')->where('openid', $v['openid'])->value('headimgurl', '');
							if ($headimgurl != $v['headimgurl'] && $v['headimgurl'] != '') {
								$downloadError = '';
								$avatar = downloadPic($v['headimgurl'], $downloadError);
								if ($avatar != '') {
									$upData['avatar'] = $avatar;
								}
							}
						} else {
							$upData = [
								'subscribe' => $v['subscribe'],
								'update_time' => time(),
							];
						}
						db('wechatUser')->where('openid', $v['openid'])->update($upData);
					}

				}

				$this->_consoleLog("同步微信公众号用户完成", 'end');

				$output->write(json_encode(['code' => 1, 'msg' => '处理成功', 'data' => []]));
			} else {
				throw new \Exception($response['errmsg']);
			}

		} catch (\Exception $e) {
			$msg = "错误:".$e->getMessage();
			$this->_consoleLog($msg, 'Exception');
		}
	}

	/**
	 * 记录日志并打印
	 *
	 * @author KING
	 * @date 2020年6月11日
	 *
	 * @param string $msg
	 * @param string $flag
	 * @param string $format
	 */
	private function _consoleLog($msg, $flag, $format=true) {
		if ($this->isPrint) consoleLog($msg, $flag, $format);
		addLog($msg, $this->logName);
	}
}